package com.usian.user.service.impl;

import com.alibaba.nacos.client.utils.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.jwt.utils.AppJwtUtil;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.dtos.LoginDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.user.feign.BehaviorFeign;
import com.usian.user.mapper.ApUserMapper;
import com.usian.user.service.ApUserLoginService;
import com.usian.utils.common.AESUtils;
import com.usian.utils.common.BCrypt;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@PropertySource("classpath:aes.properties")
public class ApUserLoginServiceImpl extends BaseServiceImpl<ApUserMapper, ApUser> implements ApUserLoginService {
    @Value("${aes-key}")
    private String keys;

    @Autowired
    private BehaviorFeign behaviorFeign;

    @Override
    public ResponseResult login(LoginDto dto) {
        //1.校验参数
        if (dto.getEquipmentId() == null && (StringUtils.isEmpty(dto.getPhone()) && StringUtils.isEmpty(dto.getPassword()))) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.手机号+密码登录
        if (!StringUtils.isEmpty(dto.getPassword())) {
            //用户登录
            ApUser dbUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            if (dbUser != null) {//用户存在                    密码+表里的随机盐转成bytes[]
                String md5Pwd = null;
                try {
                    md5Pwd = AESUtils.decryptAES(dto.getPassword(), keys);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                boolean checkpw = BCrypt.checkpw(md5Pwd, dbUser.getPassword());
                if (checkpw) {
                    Map<String, Object> map = new HashMap<>();
                    dbUser.setPassword("");
                    dbUser.setSalt("");
                    map.put("token", AppJwtUtil.getToken(dbUser.getId().longValue(), 3));
                    map.put("user", dbUser);
                    return ResponseResult.okResult(map);
                } else {
                    return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
                }
            } else {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
            }
        } else {
            //3.设备登录
            if (dto.getEquipmentId() == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            Map<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(0l, 3));
            return ResponseResult.okResult(map);

        }
    }

    //@GlobalTransactional
    @Override
    public ResponseResult register(ApUser apUser) {
        if (apUser == null || apUser.getPhone() == null || apUser.getPassword() == null) return paramError;
        ApUser one = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, apUser.getPhone()));
        if (one != null) return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "该手机号已经注册");
        if (StringUtils.isEmpty(apUser.getName())) apUser.setName(apUser.getPhone());
        if (StringUtils.isEmpty(apUser.getImage()))
            apUser.setImage("group1/M00/00/00/wKg6imNbsxmAVN1oAAX19nT0HXc158.png");
        if (apUser.getSex() == null) apUser.setSex(false);
        if (apUser.getStatus() == null) apUser.setStatus(true);
        if (apUser.getFlag() == null) apUser.setFlag((short) 1);
        if (apUser.getCreatedTime() == null) apUser.setCreatedTime(new Date());
        //对密码进行解密
        String md5Pwd = null;
        try {
            md5Pwd = AESUtils.decryptAES(apUser.getPassword(), keys);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //得到一个随机的盐值
        String gensalt = BCrypt.gensalt();
        //把密码和随机盐拼一起
        String hashpw = BCrypt.hashpw(md5Pwd, gensalt);
        apUser.setPassword(hashpw);
        boolean save = save(apUser);
        if (save) {
            ApBehaviorEntry entry = new ApBehaviorEntry();
            entry.setType((short) 1);
            entry.setEntryId(apUser.getId());
            entry.setCreatedTime(new Date());
            behaviorFeign.saveBehavior(entry);
        }
        return ResponseResult.okResult(200, "注册成功");
    }


    public static void main(String[] args) {
        String s = DigestUtils.md5DigestAsHex("12345".getBytes());
        try {
            String ss = AESUtils.encryptAES(s, "hj7x89H$yuBI0456");
            System.out.println(ss);
        } catch (Exception e) {
            e.printStackTrace();
        }
       /* String gensalt = BCrypt.gensalt();
        String hashpw = BCrypt.hashpw("12345", gensalt);
        System.out.println(hashpw);*/
    }
}
